/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.web.servlet;

import com.edu.kamai.config.Constant;
import com.edu.kamai.utility.FileName;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author xzhu
 */
public class UpLoad extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    //private String uploadRootPath = "/upload/"+Constant.upLoadMMediaFileFolder+"/";
    //private String tempPath = "/upload/"+Constant.upLoadMMediaFileFolder+"/";
    private String uploadPath = Constant.upLoadMMediaFileFolder; // 上传文件的目录
    //private String tempPath = uploadPath + "/buffer/"; // 临时文件目录";
    File tempPathFile;
    
    @Override
    public void init() throws ServletException {
        createFileFolder(uploadPath);
    }
    
    private void createFileFolder(String filePath){
        File uploadFile = new File(filePath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
        try {
            
         
            //Part a = request.getPart("string_field");
            //BufferedReader br = null;
            //br = new BufferedReader(new InputStreamReader(a.getInputStream())); 
            //String ss = null;
            /*
            while((ss = br.readLine())!=null){
                System.out.println(ss);
                uploadRootPath += ss;
                tempPath += ss+"/temp";
            }
            */
            
            //chkFileFolder();
            //System.out.append("i am here: " + a.getName() + " " + s);
            
            
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setSizeThreshold(Constant.upLoadBufferSize); // 设置缓冲区大小，这里是4kb
            factory.setRepository(tempPathFile);// 设置缓冲区目录
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            
            upload.setSizeMax(Constant.upLoadMMediaFileMaxSize); // 设置最大文件尺寸，这里是4MB
            List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
            Iterator<FileItem> i = items.iterator();

            while (i.hasNext()){
                FileItem fi = (FileItem) i.next();
                String fileName = fi.getName();
         
                //System.out.println(System.getProperty("user.dir"));
                System.out.println(fileName);
                if (fileName != null){
                    System.out.println(fileName);
                    File fullFile = new File(fileName);
                    uploadPath = FileName.getUploadFolder(fileName);
                    String absoluteFilePath = getServletContext().getRealPath(uploadPath); 
                    createFileFolder(absoluteFilePath);
                    //createFileFolder(uploadPath);
                    File savedFile = new File(absoluteFilePath, fullFile.getName());
                    
                    fi.write(savedFile);
                }
            }
            System.out.print("upload succeed");
           }catch (Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();
            } 
       }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UpLoad</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet UpLoad at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

   
    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
